package com.ycx.ycxmybatismanagement.service.Impl;

import com.ycx.ycxmybatismanagement.dto.LoginDTO;
import com.ycx.ycxmybatismanagement.mapper.LoginMapper;
import com.ycx.ycxmybatismanagement.pojo.Emp;
import com.ycx.ycxmybatismanagement.service.LoginService;
import com.ycx.ycxmybatismanagement.util.JwtUtils;
import com.ycx.ycxmybatismanagement.vo.LoginResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Override
//    @LoginErrorLog
    public LoginResultVo login(LoginDTO loginDTO) throws LoginException {
        Emp emp = loginMapper.selectUserByUsername(loginDTO.getUsername());
        if (emp.getUsername() == null){
            throw new LoginException("用户不存在,需要注册");
        }
        if (!emp.getPassword().equals(loginDTO.getPassword()) ) {
            throw new LoginException("密码错误");
        }
        //生成token
        Map<String,Object> clime  = new HashMap<>();
        clime.put("id",emp.getId());
        clime.put("username",emp.getUsername());
        clime.put("name",emp.getName());
        //用JwtUtils将token生成令牌返回浏览器
        String token = JwtUtils.generateJwt(clime);

        return new LoginResultVo(emp.getId(),emp.getUsername(), emp.getName(), token);
    }
}
